import 'package:flutter/material.dart';
import 'package:hello/old/day09Provider/store/count_model.dart';
import 'package:provider/provider.dart';

/// 1.创建自己需要的共享数据
/// 2.在应用程序的顶层ChangeNotifierProvider
/// 3.在其他位置共享数据
///  1.Consumer build方法不会重新执行
///  2.Provider.of build方法会重新执行
///  3.Selector 不需要重新构建Widget
main() {
  runApp(
      ChangeNotifierProvider(create: (ctx) => CountModel(),child: MyApp(),)
  );
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "flutter",
      home: HomePage(),
    );
  }
}

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("state"),
        centerTitle: true,
      ),
      body: Center(
        child: Column(
          children: [
            ShowData01(),
            ShowData02(),
            ElevatedButton(onPressed: (){
              print("点击");
            }, child: Text("+1"))
          ],
        ),
      ),
      floatingActionButton: Selector<CountModel,CountModel>(
        selector: (ctx,countStore) => countStore,
        shouldRebuild: (prev,next) => false,
        builder: (ctx,countStore,child){
          print("FloatingActionButton 重新构建");
          return FloatingActionButton(
            onPressed: (){
              countStore.count += 1;
            },
            child: child,
          );
        },
        child: Icon(Icons.add),
      ),
    );
  }
}

class ShowData01 extends StatelessWidget {
  const ShowData01({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    int count = Provider.of<CountModel>(context).count;
    return Text("数据 $count");
  }
}

class ShowData02 extends StatelessWidget {
  const ShowData02({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Consumer<CountModel>(
        builder: (ctx,countStore,child){
          return Text("数据 ${countStore.count}");
        }
    );
  }
}
